package chen.web.util.jdbc.wrapper;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyDriver implements Driver {

	private Driver driver;
	
	private static final Log log = LogFactory.getLog(MyDriver.class); 

	public MyDriver(String driverName){
		init(driverName);
	}
	
	public void setHandlers(List<EventHandler> handlers){
		for(EventHandler handler : handlers){
			StatementWrapper.registerHandler(handler);
		}
	}
	
	private void init(String driverName){
		try {
			Class.forName(driverName);
			Enumeration<Driver> drivers = DriverManager.getDrivers();
			while(drivers.hasMoreElements()){
				Driver driver = drivers.nextElement();
				if(driver.getClass().getName().equals(driverName)){
					DriverManager.deregisterDriver(driver);
					this.driver = driver;
					DriverManager.registerDriver(this);
					break;
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			log.fatal("找不到驱动:" + driverName, e);
			throw new RuntimeException("找不到驱动",e);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.fatal("替换驱动失败", e);
			throw new RuntimeException("替换驱动失败",e);
		}		
	}
	
	
	@Override
	public boolean acceptsURL(String url) throws SQLException {
		// TODO Auto-generated method stub
		return driver.acceptsURL(url);
	}

	@Override
	public Connection connect(String url, Properties info) throws SQLException {
		// TODO Auto-generated method stub
		Connection conn = driver.connect(url, info);
		return new ConnectionWrapper(conn);
	}

	@Override
	public int getMajorVersion() {
		// TODO Auto-generated method stub
		return driver.getMajorVersion();
	}

	@Override
	public int getMinorVersion() {
		// TODO Auto-generated method stub
		return driver.getMinorVersion();
	}

	@Override
	public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
			throws SQLException {
		// TODO Auto-generated method stub
		return driver.getPropertyInfo(url, info);
	}

	@Override
	public boolean jdbcCompliant() {
		// TODO Auto-generated method stub
		return driver.jdbcCompliant();
	}

}
